package cn.com.wxd.util;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Title:SpringContent持有类，可以使用此类获取SpingAOP实例化好的对象
 * Description:cn.com.wxd.util
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-4-14 下午3:52:38
 *
 * @author WangXuDong
 * @version 1.0
 */
public class SpringContextHolder implements ApplicationContextAware, Serializable {

    private static ApplicationContext applicationContext;

    private static final Logger log = LoggerFactory.getLogger(SpringContextHolder.class);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T)applicationContext.getBean(name);
    }


    /**
     * 从静态变量ApplicationContext中取得Bean
     */
    public static Object getBean(String name, Object obj) {
        checkApplicationContext();
        return applicationContext.getBean(name, obj);
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            log.error("无法获取到spring的ApplicationContext，请检查SpringContentHolder的文件配置！",
                    new Exception("无法获取到spring的ApplicationContext，请检查SpringContentHolder的文件配置！"));
        }
    }
}
